<!-- 查看试卷 -->
<template>
  <Spin :spinning="spinning">
    <div class="container-wrap">
      <div class="main">
        <canvas-container
          :prpopsStyle="{
            width: '100%',
            height: '100%',
          }"
          :imgList="Data.imgList"
          :tagsList="Data.tagsList"
          :isShowDownload="true"
          :jsZipName="route.query.xsXm"
        >
        </canvas-container>
      </div>

      <div class="right">
        <div class="bar-header-title">
          <span>考生姓名：{{ route.query.xsXm }}</span>
          <span @click="router.go(-1)">返回</span>
        </div>
        <div class="scllbox overflow-y-auto">
          <queryOperation :currentInfo="currentInfo" @success="getInfoDetail" />
          <choiceConfir
            :kgtDetailVOList="infoSet?.kgtDetailVOList || []"
            v-if="infoSet?.kgtDetailVOList?.length && route.query?.queryType !== 'queryScore'"
          />
          <div
            class="jdAns overflow-y-auto max-h-30vh p-10px"
            v-if="infoSet?.kgtDetailVOList?.length && route.query?.queryType === 'queryScore'"
          >
            <div
              class="w-full border-b-1 border-dashed border-gray-500 mb-10px"
              v-for="(item, index) in infoSet?.kgtDetailVOList"
              :key="`jd${index}`"
            >
              <div>
                {{ item?.tmbh || '' }}{{ item?.tmbt || '' }}：{{ item.pyZdf }}分(满分：{{
                  item?.tmfz
                }})
              </div>
              <div class="w-full flex flex-wrap px-1">
                <div class="w-1/5" v-for="(v, k) in item?.childList" :key="`jdchild${k}`">
                  <span>{{ v?.stMc || '' }}({{ v?.ckda || '' }})</span>
                  <div>
                    <div
                      v-for="(n, m) in v.childList"
                      :key="`jdchildchild${m}`"
                      :class="intersectionNum(n?.translateAnswer, v.ckda)"
                    >
                      {{ n?.translateAnswer || '' }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="score">
            <div class="header">
              <div class="line"></div>
              总分：
              <span class="number">
                {{ infoSet.toolScore ?? '--' }} <span style="font-size: 14px"> 分 </span>
              </span>
              <div class="line"></div>
            </div>
            <div class="header">
              <div style="margin-right: 10px" v-if="infoSet.kgtScore">
                客观题：<span class="number">
                  {{ infoSet.kgtScore }} <span style="font-size: 14px"> 分 </span>
                </span>
              </div>
              <div>
                评阅得分：<span class="number">
                  {{ infoSet.zgtScore ?? '--' }} <span style="font-size: 14px"> 分 </span>
                </span>
              </div>
            </div>

            <div class="table">
              <a-table
                :rowKey="record => record.stId"
                :pagination="false"
                :columns="columns(infoSet)"
                :data-source="infoSet?.zgtDetailVOList || []"
                :border="true"
                :defaultExpandAllRows="true"
                :row-selection="{
                  hideDefaultSelections: true,
                  hideSelectAll: true,
                  selectedRowKeys: Data.checkedList,
                  onChange: handelonChanChange,
                }"
                :row-class-name="
                  record => {
                    if (!!wgwjwfObj[record?.stId]) return 'bg-red-200'
                  }
                "
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'wgwjwf'">
                    {{ wgwjwfObj[record?.stId] || '否' }}
                  </template>
                  <template v-if="column.key === 'cp'">
                    <a-button
                      type="link"
                      :disabled="route.query?.queryType == 'queryScore' && currentInfo.sfyc !== 'Y'"
                      @click="handleCp(record)"
                    >
                      其他教师重评
                    </a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </div>

          <div class="score">
            <div class="font-semibold text-[18px] mb-3"> 异常记录 </div>

            <div class="table">
              <a-table
                :rowKey="record => record.stId"
                :pagination="false"
                :columns="errRolumns()"
                :data-source="Data?.errList || []"
                :scroll="{ x: 450 }"
                :border="true"
              >
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.key == 'index'">
                    <span>
                      {{ index + 1 }}
                    </span>
                  </template>
                  <template v-if="column.key === 'handle'">
                    <a-button type="link" @click="handleAbnormal(record)"> 查看 </a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </div>

          <div class="score">
            <div class="font-semibold text-[18px] mb-3"> 违规违纪违法记录 </div>

            <div class="table">
              <a-table
                :rowKey="record => record.stId"
                :pagination="false"
                :columns="wgwgwfRolumns()"
                :data-source="Data?.wgwgwfList || []"
                :scroll="{ x: 450 }"
                :border="true"
              >
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.key == 'index'">
                    <span>
                      {{ index + 1 }}
                    </span>
                  </template>
                  <template v-if="column.key === 'handle'">
                    <a-button type="link" @click="handleAbnormal(record)"> 查看 </a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <modal-visible
      v-if="abnormalVisible"
      :abnormalVisible="abnormalVisible"
      :currentTableRow="currentTableRow"
      @success="getAllPhotoList"
    />
  </Spin>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { columns, errRolumns, wgwgwfRolumns } from './data'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import CanvasContainer from '/@/layouts/components/CanvasChart/canvasContainer.vue'
import modalVisible from '/@/views/examineGrade/fraction/modalVisible.vue'
import queryOperation from '/@/views/examineGrade/fraction/queryOperation.vue'
import choiceConfir from '/@/views/examineGrade/fraction/choiceConfir.vue'
import {
  getBysuccessAutoId,
  getByKdkskmId,
  getByKdMfxkskmId,
  getBysuccessMfxAutoId,
} from '/@/api/organization/examinationPaper'
import { useTeacherMarkStore } from '/@/store/modules/teacherMark'
const teacherMarkStore = useTeacherMarkStore()
import { intersection, isMatch, split } from 'lodash-es'
import {
  querySingleDetails,
  fxcxDrjlCgsjGetByEntity,
  getImportDetail,
  getMarkingDetailsFun,
  getKssyycList,
  getKssyZkzhList,
  getWgwjwfList,
  getWgwjwfZkzhList,
} from '/@/api/queryScore'

import { Spin } from 'ant-design-vue'
//loading加载
const spinning = computed(() => teacherMarkStore.getLoading)

watch(spinning, nval => {
  if (!nval) {
    getAllPhotoList()
  }
})

dayjs.extend(duration)

const router = useRouter()
const route = useRoute()

function intersectionNum(first, second) {
  if (!first) {
    return 'text-red-500'
  }
  const ckda = split(second, '')
  const arr = intersection(split(first, ''), ckda)
  return isMatch(arr, ckda) ? 'text-green-500' : 'text-red-500'
}

const Data = reactive({
  imgList: [],
  tagsList: [],
  checkedList: [],
  errList: [],
  wgwgwfList: [],
} as any)

/**
 * 切换选中项
 */
function handelonChanChange(val, arr) {
  Data.checkedList = val
  getMarkingDetailList(arr)
}

// 获取试卷图片
async function getPageInfoFun() {
  let res: any = {}
  if (route.query?.queryType == 'queryScore') {
    res = await getBysuccessAutoId({ successAutoId: route.query?.successAutoId })
  } else {
    res = await getByKdkskmId({ kdkskmId: route.query.kdkskmId, sfsztFlag: true })
  }

  if (res.code == 200) {
    Data.imgList = res.data?.sort((a, b) => a.tpxh - b.tpxh) || []
    getInfoMfxDetail()
  }
}

/**获取密封图片 */
async function getInfoMfxDetail() {
  let mfxTpList: any = []
  if (route.query?.queryType == 'queryScore') {
    let { code, data } = await getBysuccessMfxAutoId({ successAutoId: route.query?.successAutoId })
    if (code == 200 && data.length > 0) {
      mfxTpList = data
    }
  } else {
    let { code, data } = await getByKdMfxkskmId({ kdkskmId: route.query.kdkskmId, sfsztFlag: true })
    if (code == 200 && data.length > 0) {
      mfxTpList = data
    }
  }

  for (let i = 0; i < Data.imgList.length; i++) {
    for (let j = 0; j < mfxTpList.length; j++) {
      if (Data.imgList[i].smjlid == mfxTpList[j].id) {
        Data.imgList[i].tpObj = {
          tpurl: mfxTpList[j].tpurl,
          ymlx: mfxTpList[j].ymlx, // 页面类型 1 正面  2 反面
          zzfx: mfxTpList[j].zzfx, // 纸张方向 1 向上  2 向下
        }
        break
      }
    }
  }
}

const infoSet: any = ref({})
async function getAllPhotoList() {
  let res: any = {}
  if (route.query?.queryType == 'queryScore') {
    /**查分详情 */
    res = await fxcxDrjlCgsjGetByEntity({
      zkzh: route.query.kdkskmId,
      kmdm: route.query?.kmdm,
    })
    getInfoDetail()
  } else
    res = await querySingleDetails({
      kdkskmId: route.query.kdkskmId,
      // kmdm: route.query.kmdm,
      zpDataFlag: route.query?.kmpyzt == 'FORMAL' ? 'true' : 'false',
    })

  if (res.code == 200) {
    let zgtDetailList = res.data?.zgtDetailVOList || []
    // if (zgtDetailList.length > 1) {
    //   zgtDetailList = zgtDetailList.sort((a, b) =>{
    //     console.log(a.tmxh, b.tmxh)
    //    return a.tmxh - b.tmxh
    //   })
    // }

    infoSet.value = {
      ...res.data,
      zgtDetailVOList: zgtDetailList,
      toolScore: Math.round(((res.data.kgtScore || 0) + (res.data.zgtScore || 0) || 0) * 100) / 100,
    }

    handelonChanChange(res.data?.zgtDetailVOList?.map(item => item.stId) || [], zgtDetailList || [])
  }
}

/**
 * 获取已成记录
 */
async function getInfoYcDetail() {
  if (route.query?.kmpyzt !== 'FORMAL') return
  let res: any = {}
  if (route.query?.queryType == 'queryScore') {
    res = await getKssyZkzhList({
      zkzh: route.query.kdkskmId,
      kmdm: route.query?.kmdm,
    })
  } else {
    res = await getKssyycList({
      kdkskmId: route.query?.kdkskmId,
    })
  }
  if (res.code == 200) {
    Data.errList = res.data || []
  }
}

/**
 * 获取已成记录
 */
let wgwjwfObj: any = ref({}) //获取违规违规对象

async function getInfoWgwgwfDetail() {
  if (route.query?.kmpyzt !== 'FORMAL') return
  let res: any = {}
  if (route.query?.queryType == 'queryScore') {
    res = await getWgwjwfZkzhList({
      zkzh: route.query.kdkskmId,
      kmdm: route.query?.kmdm,
    })
  } else {
    res = await getWgwjwfList({
      kdkskmId: route.query?.kdkskmId,
    })
  }
  if (res.code == 200) {
    Data.wgwgwfList = res.data || []
    for (let i = 0; i < Data.wgwgwfList.length; i++) {
      wgwjwfObj.value[Data.wgwgwfList[i].stId] = Data.wgwgwfList[i]?.remark || '是'
    }
  }
}

/**
 * 获取打分信息
 */

let dfdIdAllList: any = []

async function getMarkingDetailList(zgtDetailList: any[] = []) {
  let pySubmitIdList =
    zgtDetailList?.reduce((prev, next) => {
      prev.push(...(next?.pySubmitIdList || []))
      return prev
    }, []) || []

  if (dfdIdAllList?.length <= 0) {
    await getMarkingDetailsFun({
      pySubmitIdList,
    }).then(({ code, data }) => {
      if (code == 200) {
        Data.tagsList = []
        dfdIdAllList = data || []
      }
    })
  }
  let str = pySubmitIdList.join(',')

  getDfdList(dfdIdAllList?.filter(item => str.includes(item?.pySubmitId)) || [])
}

/**
 * 统计得分点列表
 */
function getDfdList(data: any[] = []) {
  Data.tagsList = []
  if (infoSet.value?.kgtDetailVOList?.length > 0) {
    for (let i = 0; i < infoSet.value?.kgtDetailVOList.length; i++) {
      let e = infoSet.value?.kgtDetailVOList[i]
      Data.tagsList.push({
        pyDtkqtId: Data.imgList[0].id,
        x: 100,
        y: 100 * (i + 1) + 800,
        value: e.pyZdf,
        pyDfdId: 'totleScole',
        tmbh: `${e.tmbh}${e.tmlx || ''}`,
      })
    }
  }

  data.forEach((item: any) => {
    let detaillist = item.pyDataDetailList
    if (detaillist?.length > 1) {
      detaillist = detaillist.sort((a, b) => a.sortNum - b.sortNum)
    }

    for (let i = 0; i < detaillist.length; i++) {
      let e = detaillist[i]
      let arr = e.pyLocation?.split(',')

      let x = Number(arr[0]) || 0,
        y = Number(arr[1]) || 0

      if (!e.sfszt) {
        let arr2 = e.qtLocation4ZtOnly?.split('|') || []
        if (arr2.length > 0) {
          arr2 = arr2[0].split(',')
          x += Number(arr2[0] || 0)
          y += Number(arr2[1] || 0)
        }
      }

      Data.tagsList.push({
        pyDtkqtId: e.pyDtkqtId,
        x,
        y,
        value: e.pyScore,
        pyDfdId: item.hasDfdFlag ? 'totleScole' : '',
        account: e.pyAccount,
        jsxm: e.pyJsxm,
        lfYyTyp: item.lfCode,
        lfBz: item.lfBz,
        pyMs: item.pyMs,
        tmbh: item.tmbh,
        index: i + 1,
        pySubmitIdList: item.pySubmitIdList,
      })
    }
  })
}

const currentInfo: any = ref({})
/**
 * 获取查分信息详情
 */
function getInfoDetail() {
  getImportDetail({ successAutoId: route.query?.successAutoId }).then(res => {
    currentInfo.value = res.data || {}
  })
}

// 获取阅卷教师数量
const abnormalVisible = ref(false)
const currentTableRow = ref({})

function handleCp(record: any = {}) {
  currentTableRow.value = record
  abnormalVisible.value = true
}

/**
 * 查看异常详情
 */
function handleAbnormal(record: any = {}) {
  router.push({
    name: 'ReviewPaper',
    query: {
      ycId: record.ycId,
      pyJd: 'FORMAL',
    },
  })
}

onMounted(async () => {
  getPageInfoFun()
  getAllPhotoList()
  getInfoYcDetail()
  getInfoWgwgwfDetail()
})
</script>

<style lang="less" scoped>
.container-wrap {
  display: flex;
  flex-direction: row;
  height: calc(@c_height + 32px);

  .right {
    flex: 1;
    background: #fff;
    border-radius: 5px;
    margin-left: 15px;

    .bar-header-title {
      height: 50px;
      width: 100%;
      padding-left: 20px;
      padding-right: 20px;
      display: flex;
      flex-direction: row;
      justify-items: center;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      border-bottom: 1px solid #ccc;
      font-size: 15px;
      line-height: 40px;

      span {
        cursor: pointer;
      }

      .watch-answer {
        color: #136cc4;
      }
    }

    .scllbox {
      height: calc(100% - 50px);
    }

    .score {
      padding: 16px;

      .header {
        display: flex;
        display: -webkit-flex;
        display: -ms-flexbox;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        color: #e52a2a;
        font-size: 16px;

        .number {
          font-size: 30px;
          margin-bottom: 10px;
        }
      }

      .line {
        width: 54px;
        height: 0px;
        opacity: 0.3;
        border: 1px solid #3f4355;
        margin: 10px;
      }
    }

    .table {
      border: 1px #e6e6e6 solid;
      width: 100%;

      .search {
        display: flex;
        display: -webkit-flex;
        flex-direction: row;
        align-items: center;
        margin-bottom: 15px;
        border-bottom: 1px #e6e6e6 solid;

        .img {
          width: 14px;
          height: 14px;
          margin: 0 0 0 16px;
        }

        :deep(.ant-input) {
          border: 0px transparent solid !important;
        }
      }

      .table-header {
        background: #f2f2f2;
        padding: 8px 12px;
        font-size: 14px;
        font-weight: 600;
      }

      :deep(.ant-table-thead > tr > th) {
        background: transparent !important;
      }
    }
  }

  .main {
    display: flex;
    flex-direction: row;
    width: 65%;
    height: 100%;
  }
}

.form {
  padding: 20px;
}

.answe-item {
  margin: 5px 0;
  font-size: 18px;
}
</style>
